#!/bin/bash

#==============================================================#
# File      :   install
# Ctime     :   2021-06-29
# Mtime     :   2021-06-29
# Desc      :   install pgsql monitoring system
# Path      :   app/pgsql/install
# Copyright (C) 2018-2021 Ruohang Feng
#==============================================================#

#========================================#
# detect environment
#========================================#
PROG_NAME="$(basename $0))"
PROG_DIR="$(cd $(dirname $0) && pwd)"
SQL_DIR=${PROG_DIR}/sql

DEFAULT_PIGSTY_HOMNE=${HOME}/pigsty
PIGSTY_HOME="${PIGSTY_HOME-${DEFAULT_PIGSTY_HOMNE}}"
DASHBOARD_DIR=${DASHBOARD_DIR-'/etc/dashboards'}

PIGSTY_CONFIG=${PIGSTY_HOME}/pigsty.yml

#========================================#
# create pigsty schema on meta database
#========================================#
psql service=meta -AXtwf ${SQL_DIR}/pigsty.sql

#========================================#
# finish install if PIGSTY_HOME not exists
#========================================#
if [[ ! -d ${PIGSTY_HOME} ]]; then
	echo pigsty home not found, exit
	exit 0
fi

#========================================#
# convert pigsty config into sql data
#========================================#
cat ${PIGSTY_CONFIG} | ${PIGSTY_HOME}/bin/yaml2sql pigsty > ${SQL_DIR}/data.sql
psql service=meta -AXtwf ${SQL_DIR}/data.sql

#========================================#
# replace config file with dynamic query script
#========================================#
cat > ${PIGSTY_HOME}/pigsty.yml <<-'EOF'
#!/bin/bash
psql service=meta -AXtwc 'SELECT text FROM pigsty.inventory;'
EOF
chmod 0755 ${PIGSTY_HOME}/pigsty.yml
